package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.pojo.Book;
import com.atguigu.pojo.Page;
import com.atguigu.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
    private BookDao bookDao = new BookDaoImpl();

    /**
     * 添加书
     *
     * @param book
     * @return
     */
    @Override
    public int addBook(Book book) {
        return bookDao.addBook(book);
    }

    /**
     * 根据编号删除书
     *
     * @param id
     * @return
     */
    @Override
    public int deleteBookById(Integer id) {
        return bookDao.deleteBookById(id);
    }

    /**
     * 更改书的所有属性
     *
     * @param book
     * @return
     */
    @Override
    public int upadateBook(Book book) {
        return bookDao.upadateBook(book);
    }

    /**
     * 根据编号查看书的属性
     *
     * @param id
     * @return
     */
    @Override
    public Book queryBookById(Integer id) {
        return bookDao.queryBookById(id);
    }

    /**
     * 查询所有的图书
     *
     * @return
     */
    @Override
    public List<Book> queryBooks() {
        return bookDao.queryBooks();
    }

    @Override
    public Page<Book> page(Integer pageNo, Integer pageSize) {
        Page<Book> page = new Page<>();

        //设置每页的数据
        page.setPageSize(pageSize);
        //获取总记录数
        Integer pageTotalCount = bookDao.queryForPageTotalCount();
        page.setPageTotalCount(pageTotalCount);
        //获取总页码数
        Integer pageTotal = pageTotalCount / pageSize;
        if (pageTotalCount / pageSize > 0) {
            pageTotal += 1;
        }
        //总页码
        page.setPageTotal(pageTotal);
        //当前页码
        page.setPageNo(pageNo);
        //获取当前页面的数据
        int begin = (page.getPageNo() - 1) * pageSize;
        List<Book> items = bookDao.queryForPageItems(begin, pageSize);
        page.setItems(items);
        return page;
    }

    @Override
    public Page<Book> pageByPrice(int pageNo, int pageSize, int min, int max) {
        Page<Book> page = new Page<>();

        //设置每页的数据
        page.setPageSize(pageSize);
        //获取总记录数
        Integer pageTotalCount = bookDao.queryForPageTotalCountByPrice(min,max);
        page.setPageTotalCount(pageTotalCount);
        //获取总页码数
        Integer pageTotal = pageTotalCount / pageSize;
        if (pageTotalCount / pageSize > 0) {
            pageTotal += 1;
        }
        //总页码
        page.setPageTotal(pageTotal);
        //当前页码
        page.setPageNo(pageNo);
        //获取当前页面的数据
        int begin = (page.getPageNo() - 1) * pageSize;
        List<Book> items = bookDao.queryForPageItemsByPrice(begin, pageSize,min,max);
        page.setItems(items);
        return page;
    }
}
